package com.ruoyi.rycc.core.cosUpload;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Random;

/**
 * 文件上传工具类
 *
 * @author Antg
 * @date 2021/9/7  17:15
 */
@Component
public class CosUpload {

    @Value("${spring.tengxun.secretId}")
    private String secretId;
    @Value("${spring.tengxun.secretKey}")
    private String secretKey;
    @Value("${spring.tengxun.bucket}")
    private String bucket;
    @Value("${spring.tengxun.bucketName}")
    private String bucketName;
    @Value("${spring.tengxun.path}")
    private String path;
    @Value("${spring.tengxun.prefix}")
    private String prefix;


    /**
     * @param file 需要上传到cos的文件
     * @return 返回文件的路径
     * @author Antg
     * @date 2021/9/7   17:16
     */
    public String upload(MultipartFile file) {
        // 创建 COS凭证
        COSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
        // 配置 COS 区域 就购买时选择的区域
        ClientConfig clientConfig = new ClientConfig(new Region(bucket));
        // 创建 COS 客户端连接
        COSClient cosClient = new COSClient(credentials, clientConfig);
        
        String fileName = file.getOriginalFilename();
        try {
            String substring = fileName.substring(fileName.lastIndexOf("."));
            File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), substring);
            file.transferTo(localFile);
            Random random = new Random();
            fileName = prefix + random.nextInt(10000) + System.currentTimeMillis() + substring;
            // 将 文件上传至 COS
            PutObjectRequest objectRequest = new PutObjectRequest(bucketName, fileName, localFile);
            cosClient.putObject(objectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return path + fileName;
    }
}
